package cuishifeng.blog;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.CanWriteFileFilter;
import org.apache.commons.lang3.StringUtils;

import cuishifeng.blog.helper.FileHelper;
import cuishifeng.blog.model.BlogInfo;
import cuishifeng.blog.model.BlogTitle;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cuishifeng
 * Created on 2021-01-31
 */
@Slf4j
public class MainBlog {



    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.print("文件：1-更新目录");
        String mdName = scanner.nextLine();
        if (mdName.equals("1")){
            BlogParseUtils.updateDirectory();
            return;
        }
        if (StringUtils.isBlank(mdName)) {
            log.info("MainBlog =====> 更新重建所有文档");
            createOrUpdateAllBlog();
        } else {
            log.info("MainBlog =====> 更新重建:{}", mdName);
            createOrUpdateBlog(mdName);
        }
        scanner.close();
    }


    public static void createOrUpdateAllBlog() {
            File file = FileHelper.getFile("md");
            Collection<File> files = FileUtils.listFiles(file, CanWriteFileFilter.CAN_WRITE, null);
            files.stream().map(File::getName).forEach(MainBlog::createOrUpdateBlog);
    }

    public static void createOrUpdateBlog(String mdFileName) {
        try {
            BlogInfo blogInfo = BlogParseUtils.getBlogInfo(mdFileName);
            BlogTitle blogTitle = BlogParseUtils.getBlogTitle(blogInfo);
            List<BlogTitle> blogTitles = BlogParseUtils.updateBlogListJson(blogTitle);
            BlogParseUtils.createBlogHtmlFile(blogTitle, blogInfo);
            BlogParseUtils.updateBlogHomeHtml(blogTitles);
            BlogParseUtils.updateDirectory();
        } catch (Exception e) {
            log.error("createOrUpdateBlog error", e);
        }
    }
}
